package com.pillar.game;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

import java.util.concurrent.TimeUnit;

public class NioWebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
    private final NioEventLoopGroup work;

    public NioWebSocketChannelInitializer(NioEventLoopGroup work) {
        this.work = work;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ch.pipeline().addLast(work, "logging", new LoggingHandler("INFO"));//设置log监听器，并且日志级别为debug，方便观察运行流程
        ch.pipeline().addLast("http-codec", new HttpServerCodec());//设置解码器
        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));//聚合器，使用websocket会用到
        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());//用于大数据的分区传输
        ch.pipeline().addLast(work, "readTimeoutHandler", new ReadTimeoutHandler(10, TimeUnit.SECONDS));//读取超时
        ch.pipeline().addLast(work, "writeTimeoutHandler", new WriteTimeoutHandler(30, TimeUnit.SECONDS));//写数据超时
        ch.pipeline().addLast(work, "handler", new BizHandler());//自定义的业务handler
    }
}
